local key = KEYS[1]
local rate = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])

-- 获取上次令牌生成的时间和当前令牌数
local last_tokens = tonumber(redis.call("get", key .. ".tokens"))
local last_refreshed = tonumber(redis.call("get", key .. ".timestamp"))

if last_tokens == nil then
    last_tokens = capacity
    last_refreshed = now
end

-- 计算新的令牌数
local delta = math.max(0, now - last_refreshed)
local new_tokens = math.min(capacity, last_tokens + (delta * rate))

local allowed = new_tokens >= requested
local new_timestamp = now

if allowed then
    new_tokens = new_tokens - requested
    redis.call("setex", key .. ".tokens", 60, new_tokens)
    redis.call("setex", key .. ".timestamp", 60, new_timestamp)
else
    redis.call("setex", key .. ".tokens", 60, new_tokens)
    redis.call("setex", key .. ".timestamp", 60, new_timestamp)
end

return allowed
